﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Security.Principal;
using System.Net;

namespace SimpleMVC.Filters
{
    public class GlobalAuthorizeFilter:IAuthorizationFilter
    {
        //public String Users { get; set; }
        //public String Roles { get; set; }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.IsChildAction)
            {
                return;
            }
            string accountControllerName = "Account";
            string loginActionName = "Login";
            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            if (string.Compare(accountControllerName, controllerName, true) == 0 &&
                string.Compare(loginActionName, actionName, true) == 0)
            {
                return;
            }
            var principal = filterContext.HttpContext.User;
            if (principal != null)
            {
                var identity = principal.Identity;
                if (identity != null&& identity.IsAuthenticated)
                {
                    //bool unAuthorize = string.IsNullOrEmpty(Users) && string.IsNullOrEmpty(Roles);
                    //if (unAuthorize)
                    //{
                    //    return;
                    //}
                    //string[] users = null, roles = null;
                    //if (!string.IsNullOrEmpty(Users))
                    //    users = Users.Split(',');
                    //if (!string.IsNullOrEmpty(Roles))
                    //    roles = Roles.Split(',');
                    //if (users != null && !string.IsNullOrEmpty(identity.Name))
                    //{
                    //    foreach (var user in users)
                    //    {
                    //        if (string.Compare(identity.Name, user) == 0)
                    //        {
                    //            return;
                    //        }
                    //    }
                    //}
                    //if (roles != null)
                    //{
                    //    foreach (var role in roles)
                    //    {
                    //        if (principal.IsInRole(role))
                    //        {
                    //            return;
                    //        }
                    //    }
                    //}
                    return;
                }
            }
            filterContext.Result = new HttpUnauthorizedResult("no authentication");
        }
    }
}